package com.liao.media.controller;

import com.liao.media.config.MinioConfig;
import com.liao.media.util.MinioUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: xxkfz-minio
 * @ClassName OSSController.java
 * @author: wust
 * @create: 2024-03-13 11:01
 * @description:
 **/
@Slf4j
@RestController
@RequestMapping("/oss")
public class MinioController {
    // todo 当前类需要添加统一异常处理机制？
    @Autowired
    private MinioUtils minioUtils;

    @Autowired
    private MinioConfig minioConfig;

    /**
     * 文件上传
     *
     * @param file
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) throws Exception {

//        uploadFile( MultipartFile[] files);
        MultipartFile[] multipartFiles = {file};
        List<String> urls = uploadFile(multipartFiles);
        String url = urls.get(urls.size() - 1);
        return url;
    }

    ;

    /**
     * 文件上传
     *
     * @param files
     */
    @PostMapping("/batchUpload")
    public String batchUpload(@RequestParam("files") MultipartFile[] files) throws Exception {
        List<String> urls = uploadFile(files);

        return urls.toString();
    }

    /**
     * 删除
     *
     * @param fileName
     */
    @DeleteMapping("/del")
    public void delete(@RequestParam("fileName") String fileName) {
        minioUtils.removeFile(minioConfig.getBucketName(), fileName);
    }

    /**
     * 获取文件信息
     *
     * @param fileName
     * @return
     */
    @GetMapping("/info")
    public String getFileStatusInfo(@RequestParam("fileName") String fileName) {
        return minioUtils.getFileStatusInfo(minioConfig.getBucketName(), fileName);
    }

    /**
     * 获取文件外链
     *
     * @param fileName
     * @return
     */
    @GetMapping("/url")
    public String getPresignedObjectUrl(@RequestParam("fileName") String fileName) {
        return minioUtils.getPresignedObjectUrl(minioConfig.getBucketName(), fileName);
    }

    /**
     * 文件下载
     *
     * @param fileName
     * @param response
     */
    @GetMapping("/download")
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        try {
            InputStream fileInputStream = minioUtils.getObject(minioConfig.getBucketName(), fileName);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setContentType("application/force-download");
            response.setCharacterEncoding("UTF-8");
            IOUtils.copy(fileInputStream, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载失败");
        }
    }

    /**
     * 文件上传（封装通用函数）
     *
     * @param files
     * @return
     * @throws Exception 出错抛出异常，在全局中进行处理
     */
    private List<String> uploadFile(MultipartFile[] files) throws Exception {


        List<String> urlList = new ArrayList<String>();
        for (MultipartFile file : files) {
            try {
                //文件名
                String fileName = file.getOriginalFilename();
                String newFileName = System.currentTimeMillis() + "." + StringUtils.substringAfterLast(fileName, ".");
                //类型
                String contentType = file.getContentType();
                minioUtils.uploadFile(minioConfig.getBucketName(), file, newFileName, contentType);
                String url = minioUtils.getUrl(minioConfig.getEndpoint(), minioConfig.getBucketName(), newFileName);
                urlList.add(url);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("文件上传失败", e);
            }
        }
        return urlList;
    }


}
